<template>
	<view>
		<view class="content">
			<view class="btn-box">
				<view class="btn" style="width:600rpx;height:200rpx;borderRadius:20rpx;" @click="openBluetoothAdapter">
					<view class="btn-img">
						<image :src="btnImgSrcC" mode="aspectFit" style="width: 100rpx;height:100rpx;"></image>
					</view>
					<view class="btn-text"><text style="color:#FFFFFF;fontSize:20px;">连接蓝牙设备</text></view>
				</view>
				<view class="btn btn-img1" style="width:600rpx;height:200rpx;borderRadius:20rpx; margin-top:200px;"
					@click="closeBLEConnection">
					<view>
						<image :src="btnImgSrcS" mode="aspectFit" style="width: 100rpx;height:100rpx;"></image>
					</view>
					<view class="btn-text"><text style="color:#FFFFFF;fontSize:20px;">断开蓝牙设备</text></view>
				</view>
			</view>

			<view class="uni-btn-v">

				<br>
				<view v-if="equipment.length > 0">
					{{
						(connected ? '已连接设备' : '已选择设备') +
							' : ' +
							equipment[0].name +
							' (' +
							equipment[0].deviceId +
							')'
					}}
				</view>

			</view>
		</view>
		<!-- 遮罩 -->
		<view v-if="maskShow" class="uni-mask" @touchmove.stop.prevent="moveHandle" @click="maskclose">
			<scroll-view class="uni-scroll_box" scroll-y @touchmove.stop.prevent="moveHandle" @click.stop="moveHandle">
				<view class="uni-title">
					<view>发现{{ showMaskType === 'device' ? '设备' : '个服务' }}</view>
					<loadP v-if="list.length==0"></loadP>

				</view>

				<view class="uni-list-box" v-for="(item, index) in list" :key="index" @click="tapQuery(item)">
					<view v-if="showMaskType === 'device'" class="blue-box">
						<view>
							<image :src="blueImgSrc" style="width: 60rpx;height: 60rpx;"></image>
						</view>
						<view class="uni-list_name">脑机接口设备</view>

					</view>

				</view>

			</scroll-view>
		</view>
	</view>
</template>
<script>
	import loadP from "@/components/loadPoint.vue";
	import {
		mapState,
		mapMutations
	} from 'vuex'
    import eventbus from '../../eventBus/eventbus.js'
	export default {
		components: {
			loadP
		},
		data() {
			return {
                door: 0,
				list1: [{
					name: 1
				}],
                index: 0,
                total_index: 0,
				btnImgSrcS: "../../static/icon/blueTooth/shut.png",
				btnImgSrcC: "../../static/icon/blueTooth/connect.png",
				blueImgSrc: "../../static/icon/blueTooth/blueColor.png",
				title: 'bluetooth',
				disabled: [false, true, true, true, true, true, true, true, true, true, true],
				newDeviceLoad: false,
				searchLoad: false,
				maskShow: false,
				equipment: [],
				adapterState: {
					discovering: false,
					available: false
				},
				connected: false,
				showMaskType: 'device',
				servicesData: [],
				characteristicsData: [],
				valueChangeData: {},
				isStop: true,
				list: [],
				blueToothData: [],
				number: 0,
				sendIndex: 0,
				strData: [],
				openid: "",
				handestatus:'none',
				token:null,
				sequenceId:null,
				postSize:250,
				stageList:{'left':1000,'right':1000,'rest':500,'none':2500},
				postNum:0,
				changeFlag:false,
				blueChangeNum:0
			};
		},
		onLoad() {
			this.token = uni.getStorageSync("usertoken");
			this.sequenceId = uni.getStorageSync("sequenceId");
			// this.closeBLEConnection();
			// this.closeBluetoothAdapter();
			this.strData = this.processData();
			this.onBLEConnectionStateChange();
			this.onBLECharacteristicValueChange();
			let acc = uni.getStorageSync("accountInfo");
			this.openid = acc.openid;


		},
		computed: {
			...mapState(['status'])
		},
		watch:{
			status:{
				handler(newval,oldval){
					this.handestatus = newval
				},
				immediate: true
			}
		},
		methods: {
			...mapMutations(['SET_BLUETOOTHDATAGLOBAL','SET_NUM','SET_STATUS']),

			onBLECharacteristicValueChange() {
				uni.onBLECharacteristicValueChange(characteristic => {		
					if (this.sendIndex < 19 ) {
						if (this.blueToothData.length > 0) {
							var me = this;
							let tempData = me.blueToothData;
							me.blueToothData = [];
							console.log("数据发送 任务", me.number)
							// let token = uni.getStorageSync("usertoken");
							// // let sequenceId=this.genID(20);
							// let sequenceId = uni.getStorageSync("sequenceId");
							uni.request({
								url: me.serverUrl + "/submit/toothData",
								data: {
									"data": tempData,
									"jobName": me.number,
									"openid": me.openid,
									"sequenceId": me.sequenceId
								},
								header: {
									"usertoken": me.token
								},
								method: "POST",
								success(res) {
									// console.log(res.data.status)
									me.blueToothData = []
									if (res.data.status == 200) {
										console.log(res.data)
										// uni.showToast({
										// 	title:"提交数据成功"
										// })
										me.number++;
										me.blueToothData = []
										// me.sendCode();
									}
								},
								fail: () => {
									uni.showToast({
										duration: 800,
										title: "提交数据失败"
									})
								}
							})
						}
						return;
					}
					/*************************************************/
					this.valueChangeData = characteristic;
					let handestatus = this.$store.state.status
					///// 
					// if(handestatus==='left'|| handestatus==='right' || handestatus==='none' ){
					// 	this.blueChangeNum ++
					// 	if(this.blueChangeNum % 125 === 0){
     //                        this.SET_NUM()
     //                         //console.log(this.blueChangeNum)    
     //                    }
     //                     else{
     //                        this.blueChangeNum ++
     //                        if(this.blueChangeNum % 125 === 0){
                                
     //                        this.SET_NUM()
     //                        }
     //                    }
     //                }
                    //console.log(this.blueChangeNum)
                    var time = Date.now();
                    let pushData = {};
                    pushData.time = time;
                    pushData.data = this.ab2hex(characteristic.value);
                    this.blueToothData.push(pushData);
                    eventbus.$on('begin', e => {
                        this.door = 1
                        this.blueToothData=[]
                        })
                    //eventbus.$on('stop', e => this.door = 0)
                    let data = []
                      if ((this.blueToothData.length >= this.postSize ) && (this.sendIndex >= 19) && (this.door == 1)) {
                            var _that = this
                            this.index++
                            this.SET_NUM()  //计时增加，一秒钟增加1
                            console.log('长度:' + this.blueToothData.length) 
                            console.log(this.index)
                            if(this.index > 0 && this.index <= 4) {
                                this.flag = 'left'
                            }else if(this.index > 4 && this.index <= 9) {
                                this.flag = 'none'
                                this.blueToothData=[]
                                //console.log(this.blueToothData.length);
                                //return;
                            }else if(this.index > 9 && this.index <= 13) {
                                this.flag = 'right'
                            }
                            else if(this.index > 13 && this.index <= 17) {
                                this.flag = 'rest'
                            }else if(this.index > 17 && this.index < 21) {
                                this.flag = 'none'
                                this.blueToothData=[] 
                                //return;
                            }
                            if(this.index >= 21) {
                                eventbus.$emit('resetTime', 0)
                                console.log('index>=21');
                                this.index = 0
                                this.total_index++
                                if(this.total_index >= 10) {         //总共循环次数设定，与isTraining.vue中if (this.xiaojie > N)的N一致 
                                    eventbus.$emit('resetTrian', 0)
                                    this.total_index = 0
                                    this.door = 0
                                    console.log('本次结束');
                                }
                            }  
                            
                            console.log('FLAG:' + this.flag);
                            if(this.flag == 'left' || this.flag == 'right' || this.flag == 'rest'){
                                    console.log('SEND:' + _that.flag);
                                    console.log('number' + _that.number);
                                    let data = []
                                        uni.request({
                                            url: _that.serverUrl + "/submit/toothData",
                                            data: {
                                                "data":_that.blueToothData.splice(0,_that.postSize),
                                                "jobName": _that.number,
                                                "openid": _that.openid,
                                                "sequenceId": _that.sequenceId,
                                                "type":_that.flag
                                            },
                                            header: {
                                                "usertoken": _that.token
                                            },
                                            method: "POST",
                                            success(res) {
                                                if (res.data.status == 200) {
                                                    _that.number++;
                                                    
                                                }
                                            },
                                            fail: () => {
                                                uni.showToast({
                                                    duration: 800,
                                                    title: "提交数据失败"
                                                })
                                            }
                                        })
                                    }
                        // }
					// 	if (this.blueToothData.length >= this.postSize ) {
					// 		console.log(handestatus);
     //                        var _that = this;
					// 		uni.request({
					// 			url: _that.serverUrl + "/submit/toothData",
					// 			data: {
					// 				"data":_that.blueToothData.splice(0,_that.postSize),
					// 				"jobName": _that.number,
					// 				"openid": _that.openid,
					// 				"sequenceId": _that.sequenceId,
					// 				"type":handestatus
					// 			},
					// 			header: {
					// 				"usertoken": _that.token
					// 			},
					// 			method: "POST",
					// 			success(res) {
					// 				if (res.data.status == 200) {
					// 					_that.number++;
					// 				}
					// 			},
					// 			fail: () => {
					// 				uni.showToast({
					// 					duration: 800,
					// 					title: "提交数据失败"
					// 				})
					// 			}
					// 		})
					// 	}
					}
				});
			},
			moveHandle() {},
			/**
			 * 关闭遮罩
			 */
			maskclose() {
				this.maskShow = false;
			},
			/**
			 * 选择设备
			 */
			queryDevices() {
				// this.newDeviceLoad = true;
				this.showMaskType = 'device';
				this.maskShow = true;
			},
			tapQuery(item) {
				if (this.showMaskType === 'device') {
					this.$set(this.disabled, 4, false);
					if (this.equipment.length > 0) {
						this.equipment[0] = item;
					} else {
						this.equipment.push(item);
					}
					this.newDeviceLoad = false;

					this.createBLEConnection(); //连接
					this.maskShow = false;
				}
				if (this.showMaskType === 'service') {
					console.log("item", item);
					this.$set(this.disabled, 6, false);
					if (this.servicesData.length > 0) {
						this.servicesData[0] = item;
					} else {
						this.servicesData.push(item);
					}
					this.getBLEDeviceCharacteristics(); //获取设备特征码
				}
				if (this.showMaskType === 'characteristics') {
					this.$set(this.disabled, 7, false);
					console.log("分割！")
					if (this.characteristicsData.length > 0) { //这里的方法写的同样是狗屎
						this.characteristicsData[0] = item;
					} else {
						this.characteristicsData.push(item);
					}

				}
				this.maskShow = false;

			},
			/**
			 * 初始化蓝牙设备
			 */
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e.errMsg);
						console.log(JSON.stringify(e));
						this.isStop = false;
						this.$set(this.disabled, 0, true);
						this.$set(this.disabled, 1, false);
						this.$set(this.disabled, 10, false);
						this.getBluetoothAdapterState();

						this.startBluetoothDevicesDiscovery(); //搜索
					},
					fail: e => {
						console.log(e)
						plus.nativeUI.toast('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg))
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
						if (e.errCode !== 0) {
							initTypes(e.errCode, e.errMsg);
						}
					}
				});
			},
			/**
			 * 开始搜索蓝牙设备
			 */
			startBluetoothDevicesDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					success: e => {
						console.log('开始搜索蓝牙设备:' + e.errMsg);
						this.searchLoad = true;
						this.$set(this.disabled, 1, true);
						this.$set(this.disabled, 2, false);
						this.$set(this.disabled, 3, false);
						this.onBluetoothDeviceFound(); //监听发现的蓝牙设备

						this.queryDevices(); //这里逻辑开始不合理 选择设备？？？？

					},
					fail: e => {
						console.log('搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery(types) {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
						if (types) {
							this.$set(this.disabled, 1, true);
						} else {
							this.$set(this.disabled, 1, false);
						}
						this.$set(this.disabled, 2, true);
						// this.$set(this.disabled, 3, true);
						this.searchLoad = false;


					},
					fail: e => {
						plus.nativeUI.toast('停止搜索蓝牙设备失败，错误码：' + e.errCode)
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 发现外围设备   在监听发现设备api种又调用另一个获取原来蓝牙模块发现的设备api
			 */
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound(devices => {
					// console.log('开始监听寻找到新设备的事件');
					// this.$set(this.disabled, 3, false);
					this.getBluetoothDevices(); //这是模块之前已发现的设备
				});
			},
			/**
			 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			 */
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						this.newDeviceLoad = false;
						// console.log('获取蓝牙设备成功:' + res.errMsg);
						// console.log(JSON.stringify(res))
						// this.list = res.devices;
						let arr = [];
						for (let i = 0; i < res.devices.length; i++) {
							if (res.devices[i].name[0] == 'S' && res.devices[i].name[1] == 'i') {
								// console.log(res.devices[i].name)
								arr.push(res.devices[i]);
								break;
							}
						}
						this.list = arr;
						// console.log(this.list)
					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			//不知道干嘛的函数
			processData() {
				let strList = [];
				strList[0] = "s";
				strList[1] = "v";
				strList[2] = "/0";
				strList[3] = "x1060110X";
				strList[4] = "x2060110X";
				strList[5] = "x3060110X";
				strList[6] = "x4060110X";
				strList[7] = "x5060110X";
				strList[8] = "x6060110X";
				strList[9] = "x7060110X";
				strList[10] = "x8060110X";

				strList[11] = "xQ060110X";
				strList[12] = "xW060110X";
				strList[13] = "xE060110X";
				strList[14] = "xR060110X";
				strList[15] = "xT060110X";
				strList[16] = "xY060110X";
				strList[17] = "xU060110X";
				strList[18] = "xI060110X";

				strList[19] = "b";
				return strList;
			},
			//转换二进制数据
			hexStringToArrayBuffer(str) {

				var buffer = new ArrayBuffer(str.length);
				let dataView = new DataView(buffer)
				let ind = 0;
				for (var i = 0, len = str.length; i < len; i += 2) {
					let code = parseInt(str.substr(i, 2), 16)
					dataView.setUint8(ind, code)
					ind++
				}
				return buffer;
			},

			// 字符串转byte
			stringToBytes(str) {
				var array = new Uint8Array(str.length);
				for (var i = 0, l = str.length; i < l; i++) {
					array[i] = str.charCodeAt(i);
				}
				console.log(array);
				return array.buffer;
			},
			/*向蓝牙设备中写入数据
				@parmas  deviceId 蓝牙设备 id
				@parmas	 serviceId	蓝牙特征值对应服务的 uuid
				@parmas  characteristicId 蓝牙特征值的 uuid
				@parmas	 value	ArrayBuffer	蓝牙设备特征值对应的二进制值
			*/

			// let deviceId = this.equipment[0].deviceId;
			// let serviceId = this.servicesData[0].uuid;
			// let characteristicId = this.characteristicsData[0].uuid;

			//写入成功后，设备就会通过广播 onBLECharacteristicValueChange方法 将数据返回给我们
			writeBLECharacteristicValue() {
				let me = this;
				let str = this.strData[this.sendIndex];

				let buffer = this.stringToBytes(str);


				uni.writeBLECharacteristicValue({
					deviceId: this.equipment[0].deviceId,
					serviceId: this.servicesData[0].uuid,
					characteristicId: this.characteristicsData[0].uuid,
					value: buffer,
					success: res => {
						// console.log(res)
						console.log("脑机设备握手中", str)
						if (this.sendIndex < 19) {
							setTimeout(function() {
								me.sendIndex++;
								me.writeBLECharacteristicValue();
							}, 100)
							// this.sendIndex++;
							// this.writeBLECharacteristicValue();
						}
					},
					fail: err => {
						console.error("握手写入失败", err)
					},
					complete: (resD) => {
						console.log(resD)
					}
				})
			},

			/**
			 * 获取本机蓝牙适配器状态
			 */
			getBluetoothAdapterState() {
				try {
					console.log('--->');
					uni.getBluetoothAdapterState({
						success: res => {
							console.log(JSON.stringify(res));
							this.adapterState = res;
						},
						fail: e => {
							console.log('获取本机蓝牙适配器状态失败，错误码：' + e.errCode);
							if (e.errCode !== 0) {
								initTypes(e.errCode);
							}
						}
					});
				} catch (e) {
					//TODO handle the exception
					plus.nativeUI.alert(e)
				}

			},

			/**
			 * 断开与低功耗蓝牙设备的连接
			 */
			closeBLEConnection() {
				let deviceId = this.equipment[0].deviceId;
				uni.closeBLEConnection({
					deviceId,
					success: res => {
						console.log(res);
						console.log('断开低功耗蓝牙成功:' + res.errMsg);

						this.$set(this.disabled, 1, false);
						this.$set(this.disabled, 3, true);
						this.$set(this.disabled, 4, true);
						this.$set(this.disabled, 5, true);
						this.$set(this.disabled, 6, true);
						this.$set(this.disabled, 7, true);
						this.$set(this.disabled, 8, true);
						this.$set(this.disabled, 9, true);
						this.equipment = [];
						this.servicesData = [];
						this.characteristicsData = [];

					},
					fail: e => {
						console.log('断开低功耗蓝牙成功，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},

			/**
			 * 连接低功耗蓝牙
			 */
			createBLEConnection() {
				let deviceId = this.equipment[0].deviceId;
				//把设备id存进store
				this.$store.commit('SET_BLUETOOTHDEVICEID', deviceId)
				uni.showToast({
					title: '连接蓝牙...',
					icon: 'loading',
					duration: 99999
				});
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success: res => {
						console.log(res);
						console.log('连接蓝牙成功:' + res.errMsg);
						// 连接设备后断开搜索 并且不能搜索设备
						this.stopBluetoothDevicesDiscovery(true);
						uni.hideToast();
						uni.showToast({
							title: '连接成功',
							icon: 'success',
							duration: 2000
						});
						uni.setStorageSync("connectBlue", true);
						this.$set(this.disabled, 3, true);
						this.$set(this.disabled, 4, true);
						this.$set(this.disabled, 5, false);
						this.$set(this.disabled, 9, false);
						this.connected = true;
						let _this = this;
						setTimeout(function() {
							_this.getBLEDeviceServices();
						}, 2000);
						// this.getBLEDeviceServices();
						//连接成功返回上一页
						
					},
					fail: e => {
						console.log('连接低功耗蓝牙失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 获取所有服务
			 */
			getBLEDeviceServices() {
				let deviceId = this.equipment[0].deviceId;
				console.log('获取所有服务的 uuid:' + deviceId);

				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success: res => {
						console.log(JSON.stringify(res.services));
						console.log('获取设备服务成功:' + res.errMsg);
						console.log(res.services)
						this.$set(this.disabled, 7, true);
						this.$set(this.disabled, 8, true);
						this.showMaskType = 'service1';
						this.list = res.services;
						this.maskShow = false;
						this.characteristicsData = [];
						if (this.list.length <= 0) {
							toast('获取服务失败，请重试!');
							return;
						}
						// this.maskShow = true;

						this.tapQuery(this.list[3])
						//这里获取到的服务要存进全局 在训练页面调用

						this.$store.commit('SET_BLUETOOTHSEVER', this.list)
						plus.nativeUI.toast(this.list[3])
						uni.navigateBack({
							delta: 1
						});
					},
					fail: e => {
						console.log('获取设备服务失败，错误码：' + e.errCode);
						// if (e.errCode !== 0) {
						// 	initTypes(e.errCode);
						// }
					}
				});
			},
			//转字符串
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},

			/**
			 * 获取某个服务下的所有特征值
			 */
			getBLEDeviceCharacteristics() {
				let deviceId = this.equipment[0].deviceId;
				let serviceId = this.servicesData[0].uuid;
				let me = this;
				console.log(deviceId);
				console.log(serviceId);
				uni.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId,
					success: res => {
						console.log(res);
						console.log('获取特征值成功:' + res.errMsg);
						this.$set(this.disabled, 7, true);
						this.valueChangeData = {};
						this.showMaskType = 'characteristics';
						this.list = res.characteristics;
						if (this.list.length <= 0) {
							toast('获取特征值失败，请重试!');
							return;
						}
						this.characteristicsData.push(res.characteristics[0]);
						// this.characteristicsData.push(res.characteristics[2]);
						setTimeout(function() {
							me.writeBLECharacteristicValue();
						}, 2000)
						// this.writeBLECharacteristicValue();
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							if (item.properties.read) {
								//读取低功耗蓝牙设备的特征值的二进制数据值。1
								uni.readBLECharacteristicValue({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
								})
							}

							if (item.properties.notify || item.properties.indicate) {
								//启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
								uni.notifyBLECharacteristicValueChange({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
									state: true,
								});

							}
						}
						this.maskShow = false;

					},
					fail: e => {
						console.log('获取特征值失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},

			/**
			 * 读取低功耗蓝牙设备的特征值的二进制数据值。注意：必须设备的特征值支持 read 才可以成功调用
			 */
			readBLECharacteristicValue() {
				let deviceId = this.equipment[0].deviceId;
				let serviceId = this.servicesData[0].uuid;
				let characteristicId = this.characteristicsData[0].uuid;
				uni.readBLECharacteristicValue({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId,
					success: res => {
						console.log('读取设备数据值成功');
						console.log(JSON.stringify(res));
						this.notifyBLECharacteristicValueChange();
					},
					fail(e) {
						console.log('读取设备数据值失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
				this.onBLECharacteristicValueChange();
			},
			genID(length) {
				return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
			},

			/**
			 * 订阅操作成功后需要设备主动更新特征值的 value，才会触发 uni.onBLECharacteristicValueChange 回调。
			 */
			notifyBLECharacteristicValueChange() {
				let deviceId = this.equipment[0].deviceId;
				let serviceId = this.servicesData[0].uuid;
				let characteristicId = this.characteristicsData[0].uuid;
				let notify = this.characteristicsData[0].properties.notify;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId,
					success(res) {
						console.log('notifyBLECharacteristicValueChange success:' + res.errMsg);
						console.log(JSON.stringify(res));
					}
				});
			},



			/**
			 * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接，设备丢失，连接异常断开等等
			 */

			onBLEConnectionStateChange() {
				uni.onBLEConnectionStateChange(res => {
					// 该方法回调中可以用于处理连接意外断开等异常情况
					console.log(`蓝牙连接状态 -------------------------->`);
					console.log(JSON.stringify(res));
					if (!res.connected) {
						if (this.isStop) return;
						console.log('断开低功耗蓝牙成功:');
						this.$set(this.disabled, 1, false);
						this.$set(this.disabled, 3, true);
						this.$set(this.disabled, 4, true);
						this.$set(this.disabled, 5, true);
						this.$set(this.disabled, 6, true);
						this.$set(this.disabled, 7, true);
						this.$set(this.disabled, 8, true);
						this.$set(this.disabled, 9, true);
						this.searchLoad = false;
						this.equipment = [];
						this.servicesData = [];
						this.characteristicsData = [];
						this.valueChangeData = {};
						uni.setStorageSync("connectBlue", false);
						toast('已经断开当前蓝牙连接');
					}

				});
			},


			/**
			 * 	断开蓝牙模块
			 */

			closeBluetoothAdapter(OBJECT) {
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('断开蓝牙模块成功');
						this.isStop = true;
						this.$set(this.disabled, 0, false);
						this.$set(this.disabled, 1, true);
						this.$set(this.disabled, 2, true);
						this.$set(this.disabled, 3, true);
						this.$set(this.disabled, 4, true);
						this.$set(this.disabled, 5, true);
						this.$set(this.disabled, 6, true);
						this.$set(this.disabled, 7, true);
						this.$set(this.disabled, 8, true);
						this.$set(this.disabled, 9, true);
						this.$set(this.disabled, 10, true);
						this.equipment = [];
						this.servicesData = [];
						this.characteristicsData = [];
						this.valueChangeData = {};
						this.adapterState = [];
						this.searchLoad = false;
						toast('断开蓝牙模块');
					}
				});
			}
		}
	};

	/**
	 * 判断初始化蓝牙状态
	 */
	function initTypes(code, errMsg) {
		switch (code) {
			case 10000:
				toast('未初始化蓝牙适配器');
				break;
			case 10001:
				toast('未检测到蓝牙，请打开蓝牙重试！');
				break;
			case 10002:
				toast('没有找到指定设备');
				break;
			case 10003:
				toast('连接失败');
				break;
			case 10004:
				toast('没有找到指定服务');
				break;
			case 10005:
				toast('没有找到指定特征值');
				break;
			case 10006:
				toast('当前连接已断开');
				break;
			case 10007:
				toast('当前特征值不支持此操作');
				break;
			case 10008:
				toast('其余所有系统上报的异常');
				break;
			case 10009:
				toast('Android 系统特有，系统版本低于 4.3 不支持 BLE');
				break;
			default:
				toast(errMsg);
		}
	}

	/**
	 * 弹出框封装
	 */
	function toast(content, showCancel = false) {
		uni.showModal({
			title: '提示',
			content,
			showCancel
		});
	}
</script>

<style>
	@import url("blue-tooth.css");
</style>
